#include "EngineHeader.h"

namespace LSH
{

//------------------------------------------------------------------------
VertexBuffer::VertexBuffer(void):_size(0), _d3dFVF(0), _pD3dVB(0)
{
}

//------------------------------------------------------------------------
VertexBuffer::~VertexBuffer(void)
{
    DXH_SAFE_RELEASE(_pD3dVB);
}

//------------------------------------------------------------------------
void VertexBuffer::create(UINT size, UINT count, DWORD d3dFVF)
{
    DXH_SAFE_RELEASE(_pD3dVB);
    bool ret = SUCCEEDED(Rander::GetSingleton().getD3DDevice()->CreateVertexBuffer(size * count,
                        0, d3dFVF, 
                        D3DPOOL_DEFAULT, 
                        &_pD3dVB , NULL));
    assert(ret);
    _size = size;
    _count = count;
    _d3dFVF = d3dFVF;
}

//------------------------------------------------------------------------
void* VertexBuffer::lock(UINT size)
{
    void* pVertices = NULL;
    bool ret = false;
    if(size == 0 || size > _size)
    {
        ret = SUCCEEDED(_pD3dVB->Lock(0, _size, (void**)&pVertices, 0));
        assert(ret);
    }
    else
    {
        ret = SUCCEEDED(_pD3dVB->Lock(0, size, (void**)&pVertices, 0));
        assert(ret);
    }
    return pVertices;
}

//------------------------------------------------------------------------
void VertexBuffer::unlock()
{
    _pD3dVB->Unlock();
}

//------------------------------------------------------------------------
void VertexBuffer::map(void* pVertices, UINT size)
{
    void* pMemory = lock();
    memcpy(pMemory, pVertices, size);
    unlock();
}

//------------------------------------------------------------------------
void VertexBuffer::SetAsStreamSource()
{
    IDirect3DDevice9* pDevice = Rander::GetSingleton().getD3DDevice();
    pDevice->SetStreamSource(0, _pD3dVB, 0, _size);
    pDevice->SetFVF(_d3dFVF);
}

} // LSH
